<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 分类列表区域 -->
      <tree-table
        :data="categoryList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
        class="treeTable"
      >
        <template slot="isok" slot-scope="scope">
          <i
            v-if="!scope.row.cat_deleted"
            class="el-icon-success"
            style="color: lightgreen"
          ></i>
          <i v-else class="el-icon-error" style="color: red"></i>
        </template>
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level === 1" type="success"
            >二级</el-tag
          >
          <el-tag v-else type="warning">三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <!-- 修改按钮 -->
          <el-button
            type="primary"
            :id="scope.row.id"
            icon="el-icon-edit"
            size="mini"
            @click="showEditDialog(scope.row.id)"
            >编辑</el-button
          >
          <!-- 删除按钮 -->
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="removeCateById(scope.row.id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addDialogVisible"
      width="30%"
      @close="resetAddDialogClosed"
    >
      <el-form
        ref="addFormRef"
        :model="addCateForm"
        :rules="addCateFormRules"
        label-width="70px"
      >
        <el-form-item label="分类名称" prop="cat_name" label-width="100px">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类" label-width="100px">
          <!-- options: 指定数据源 -->
          <!-- props： 指定配置对象 -->
          <el-cascader
            expand-trigger="hover"
            v-model="selectedKeys"
            :options="parentCategoryList"
            :props="cascaderProps"
            clearable
            @change="parentCateChanged"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'categories',
  data() {
    return {
      categoryList: [],
      total: 0,
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
          width: '400px'
        },
        {
          label: '是否有效',
          type: 'template' /* 表示将当前列设为模板列 */,
          template: 'isok' /* 模板名称 */
        },
        {
          label: '排序',
          type: 'template' /* 表示将当前列设为模板列 */,
          template: 'order' /* 模板名称 */
        },
        {
          label: '操作',
          type: 'template' /* 表示将当前列设为模板列 */,
          template: 'opt' /* 模板名称 */
        }
      ],
      queryInfo: {
        type: 3,
        pagenum: 1 /* 当前页数 */,
        pagesize: 5 /* 当前每页显示多少条数据 */
      },
      addDialogVisible: false,
      addCateForm: {
        cat_name: '',
        cat_pid: 0 /* 父级分类 */,
        cat_level: 0 /* 默认是一级分类 */
      },
      addCateFormRules: {
        cat_name: [{ required: true, message: '请输入分类名称', triger: blur }]
      },
      parentCategoryList: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      /* 选中的父级分类的id */
      selectedKeys: []
    }
  },
  created() {
    this.getCategoryList()
  },
  methods: {
    /* 获取商品分类数据 */
    async getCategoryList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error('获取商品分类失败')
      this.categoryList = res.data.result
      this.total = res.data.total
    },
    /* 监听pagesize改变 */
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCategoryList()
    },
    /* 监听pagenum的改变 */
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getCategoryList()
    },
    /* 获取父级分类的列表 */
    async getParentCategroiesList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) return this.$message.error('获取父级分类失败')
      this.parentCategoryList = res.data
      console.log(res.data)
    },
    showAddDialog() {
      this.getParentCategroiesList()
      this.addDialogVisible = true
    },
    resetAddDialogClosed() {
      this.$refs.addFormRef.resetFields()
      this.selectedKeys = []
      this.addCateForm.cat_level = 0
      this.addCateForm.cat_pid = 0
    },
    parentCateChanged() {
      console.log(this.selectedKeys)
      /* 如果 selectedKeys 的length大于0 证明选中的父级分类 */
      /* 反之 没有选中任何父级分类 */
      if (this.selectedKeys.length > 0) {
        /* 父级分类的id */
        this.selectedKeys.cat_pid = this.selectedKeys[
          this.selectedKeys.length - 1
        ]
        /* 为当前分类的等级赋值 */
        this.addCateForm.cat_level = this.selectedKeys.length
        return true
      } else {
        /* 父级分类的Id */
        this.addCateForm.cat_pid = 0
        /* 为当前分类的等级赋值 */
        this.addCateForm.cat_level = 0
      }
    },
    addCate() {
      console.log(this.addCateForm)
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          'categories',
          this.addCateForm
        )
        if (res.meta.status !== 201) return this.$message.error('添加分类失败')
        this.$message.success('添加分类成功！')
        this.getCategoryList()
        this.addDialogVisible = false
      })
    }
  }
}
</script>
<style lang="less" scoped>
.treeTable {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>
